package com.sgcc.pda.hw.binder;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.sgcc.pda.common.aidl.CommonCallback;
import com.sgcc.pda.common.aidl.CommonParams;
import com.sgcc.pda.common.aidl.CommonResults;
import com.sgcc.pda.hw.IHardwareManager;
import com.sgcc.pda.CommonResultsConstant;

import java.lang.reflect.Method;

/**
 * Hardware基础服务接口-封装给插件APP通过Binder调用
 *
 * @author Ben
 * @date 2019/06/11
 */
public class HardwareBinderUtil {
    /**
     * 成功字段
     */
    private static final String SUCCESS = "success";
    /**
     * 是否设置成功
     */
    private static final String IS_SUCCESS = "isSuccess";
    private static final String TAG = "HardwareBinderUtil";
    static final String CLASS_NAME = "com.sgcc.pda.hw.binder.HardwareBinderUtil";

    private IHardwareManager mService = null;
    private boolean isBind = false;

    private ServiceConnection mConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mService = IHardwareManager.Stub.asInterface(service);
            isBind = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBind = false;
            mService = null;
        }
    };

    private HardwareBinderUtil() {
    }

    private static class Instance {
        private static final HardwareBinderUtil mInstance = new HardwareBinderUtil();
    }

    /**
     * 单例
     */
    public static HardwareBinderUtil getInstance() {
        return Instance.mInstance;
    }

    /**
     * 绑定掌机基础服务提供接口的AIDL服务
     *
     * @param context
     * @return 是否绑定
     */
    public boolean bind(Context context) {
        if (isBind) return true;
        Intent intent = new Intent("com.sgcc.pda.hw.AIDL_HARDWARE_SERVICE");
        intent.setPackage("com.sgcc.pda.hw");
        try {
            isBind = context.bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        } catch (SecurityException e) {
            Log.e(TAG, "bind: " + e.getMessage());
            isBind = false;
        }
        return isBind;
    }

    /**
     * 取消绑定掌机基础服务提供接口的AIDL服务
     *
     * @param context
     * @return 是否绑定
     */
    public void unbind(Context context) {
        try {
            context.unbindService(mConnection);
        } catch (Exception e) {
            Log.e(TAG, "unbind: " + e.getMessage());
        }
    }

    /**
     * 根据方法名执行对应的方法
     *
     * @param params   参数
     * @param callback 回调
     * @return 结果
     */
    public CommonResults execute(CommonParams params, CommonCallback callback) {
        String methodName = params.getMethodName();
        try {
            // 通过反射调用方法，方法参数与返回值必须统一成（CommonParams，CommonCallback，CommonResults）
            Method method = getClass().getMethod(methodName, CommonParams.class, CommonCallback.class);
            return (CommonResults) method.invoke(this, params, callback);
        } catch (Exception e) {
            Log.e(TAG, "execute: " + e.getMessage());
            return new CommonResults(CommonResultsConstant.ERROR_METHOD_INVOKE_EXCEPTION.getCode(), CommonResultsConstant.ERROR_METHOD_INVOKE_EXCEPTION.getMsg());
        }
    }

    /**
     * 获取安全单元信息(不建议使用广播；使用回调吧)
     * <p>
     * broadcastName 获取结果的广播名称
     */

    public CommonResults getSafetyUnit(CommonParams params, CommonCallback callback) throws RemoteException {
        String broadcastName = params.getString("broadcastName");
        mService.getSafetyUnit(broadcastName);
        return new CommonResults("1", SUCCESS);
    }


    /**
     * 检测登录
     * <p>
     * password 密码
     *
     * @return String
     */
    public CommonResults checkUserPassword(CommonParams params, CommonCallback callback) throws RemoteException {
        String password = params.getString("password");
        String value = mService.checkUserPassword(password);
        CommonResults results = new CommonResults("1", SUCCESS);
        results.addResult("checkResult", value);
        return results;
    }


    /**
     * 设置系统时钟
     * <p>
     * dateTime 设置日期时间值的字符串yyyy-MM-dd HH:mm:ss，如2016-10-28 16:34:45
     *
     * @return 成功返回 true，失败返回 false
     */
    public CommonResults setDateTime(CommonParams params, CommonCallback callback) throws RemoteException {
        String dateTime = params.getString("dateTime");
        boolean value = mService.setDateTime(dateTime);
        CommonResults results = new CommonResults("1", SUCCESS);
        results.addResult(IS_SUCCESS, value);
        return results;
    }

    /**
     * 添加 APN 设置，同时设置为默认
     * <p>
     * apnName  APN 设置的名称标识
     * apn      APN   内容
     * userName 用户名，可为空或 null
     * password 密码，可为空或 null
     *
     * @return 成功返回 true，失败返回 false
     */
    public CommonResults addApn(CommonParams params, CommonCallback callback) throws RemoteException {
        String apnName = params.getString("apnName");
        String apn = params.getString("apn");
        String userName = params.getString("userName");
        String password = params.getString("password");

        boolean value = mService.addApn(apnName, apn, userName, password);
        CommonResults results = new CommonResults("1", SUCCESS);
        results.addResult(IS_SUCCESS, value);
        return results;
    }

    /**
     * 复制so
     *
     * @return 成功返回 true，失败返回 false
     */
    public CommonResults copySo(CommonParams params, CommonCallback callback) throws RemoteException {
        boolean value = mService.copySo();
        CommonResults results = new CommonResults("1", SUCCESS);
        results.addResult(IS_SUCCESS, value);
        return results;
    }

}
